/**
 * Created by youngpan on 2017/1/7.
 */
define(['app','require', 'module/category/controller'], function (app,require) {


    app.controller('tabBoxCtrl', function ($scope) {
        //用数组来保存所有的手风琴组
        this.groups = [];
        //关闭函数 如果只留一个当前开启的。
        this.closeOthers = function (openGroup) {
            angular.forEach(this.groups, function (group) { //遍历所有的手风琴组
                if (group !== openGroup) { //如果没有规定打开的手风琴组，就全部关闭
                    group.isOpen = false;
                }
            })
        };
        //要向手风琴组添加对象时调用的函数
        this.addGroup = function (groupScope) { //添加的是作用域
            var that = this;
            this.groups.push(groupScope);
        };
        //要移除手风琴组时候调用，需要移除数组中对应的项
        this.removeGroup = function (group) {
            var index = this.groups.indexOf(group);
            if (index !== -1) {
                this.groups.splice(index, 1);
            }
        };
    })

    app.directive('tabBox', function () {
        return {
            controller: 'tabBoxCtrl',
            controllerAs: 'tabBox',
            link: function (scope, ele, atte) {
            }
        }
    });

    app.directive('tabItem', function () {
        return {
            require: '^tabBox',
            scope: {
                isOpen: '=?',//=双向绑定
                title: '@',
                titleid:'@'
            },
            replace: true,
            templateUrl: 'tpls/tabitem.html',
            controller: function ($scope,$http,$route) {
                $scope.isOpen = false;
                $scope.showTab = function (id) {
                    //关闭所有。
                    id = Number(id);
                    //优化，没有再进行数据请求。
                    //todo
                    $http({
                        type:'GET',
                        url:'http://192.168.127.222:9090/api/getcategory',
                        cache:true,
                        params:{
                            titleid:id
                        }
                    }).then(function(data){
                        $scope.allcategory = data.data.result;
                    })
                    $scope.isOpen = !$scope.isOpen;
                }
            },
            link: function (scope, element, attrs, tabBoxCtrl) {
                //把当前scope添加进 手风琴数组
                tabBoxCtrl.addGroup(scope);
                //设置展开的样式
                //监听isOpen，判断是否发生变化
                scope.$watch('isOpen', function (newValue) {
                    if (newValue) {
                        tabBoxCtrl.closeOthers(scope);
                    }
                });

            }
        }
    })

})